<template>
  <div class="userlist-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input v-model="searchForm.userName" placeholder="用户名称/用户ID/手机号码" clearable @keyup.enter="handleSearch"
            style="width: 240px">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="用户状态" clearable style="width: 120px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 240px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="exportUserList">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出列表</span>
          </el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="userList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="用户ID" width="100" align="center" />
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名称" min-width="120" />
        <el-table-column prop="phone" label="手机号码" width="130" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === 'male' ? '男' : row.gender === 'female' ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ formatStatus(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="viewUserDetail(row)">查看</el-button>
              <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
              <el-button size="small" :type="row.status === 'disabled' ? 'success' : 'danger'"
                @click="toggleUserStatus(row)">
                {{ row.status === 'disabled' ? '启用' : '禁用' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="650px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ currentUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          {{ currentUser.gender === 'male' ? '男' : currentUser.gender === 'female' ? '女' : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="年龄">{{ currentUser.age }}</el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ currentUser.registerTime }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
            :type="currentUser.status === 'normal' ? 'success' : currentUser.status === 'disabled' ? 'danger' : 'info'">
            {{ currentUser.status === 'normal' ? '正常' : currentUser.status === 'disabled' ? '禁用' : '未验证' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册来源">{{ currentUser.source }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ currentUser.address }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentUser.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="editForm.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="editForm.age" :min="0" :max="120" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
            <el-option label="未验证" value="unverified" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editForm.address" type="textarea" rows="2" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Download } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';

// 搜索表单
const searchForm = reactive({
  userId: '',
  userName: '',
  phone: '',
  dateRange: [] as string[],
  status: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '正常', value: 'normal' },
  { label: '禁用', value: 'disabled' },
  { label: '未验证', value: 'unverified' }
];

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 加载状态
const loading = ref(false);

// 用户列表数据
const userList = ref([]);

// 当前选中的用户
const currentUser = ref({
  id: '',
  userName: '',
  phone: '',
  email: '',
  gender: '',
  age: 0,
  registerTime: '',
  lastLoginTime: '',
  status: '',
  source: '',
  address: '',
  remark: '',
  avatar: ''
});

// 对话框控制
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 编辑表单
const editForm = reactive({
  id: '',
  userName: '',
  phone: '',
  email: '',
  gender: '',
  age: 0,
  status: '',
  address: '',
  remark: ''
});

// 编辑表单规则
const editRules = {
  userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ]
};

const editFormRef = ref<FormInstance>();

// 页面加载时获取数据
onMounted(() => {
  getUserList();
});

// 获取用户列表
const getUserList = () => {
  loading.value = true;

  // 模拟接口请求，实际项目中应替换为真实的API调用
  setTimeout(() => {
    const mockUsers = Array.from({ length: 100 }, (_, index) => {
      const id = (index + 1).toString().padStart(6, '0');
      const status = ['normal', 'disabled', 'unverified'][Math.floor(Math.random() * 3)];
      const gender = ['male', 'female', 'unknown'][Math.floor(Math.random() * 3)];

      return {
        id,
        userName: `用户${id}`,
        phone: `1${Math.floor(Math.random() * 9 + 3)}${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
        email: `user${id}@example.com`,
        gender,
        age: Math.floor(Math.random() * 60) + 18,
        registerTime: new Date(Date.now() - Math.floor(Math.random() * 90 * 24 * 60 * 60 * 1000)).toLocaleString(),
        lastLoginTime: new Date(Date.now() - Math.floor(Math.random() * 10 * 24 * 60 * 60 * 1000)).toLocaleString(),
        status,
        source: ['App注册', '微信', 'Web注册', '邀请注册'][Math.floor(Math.random() * 4)],
        address: '广东省深圳市南山区科技园',
        remark: '系统默认生成的用户',
        avatar: `https://randomuser.me/api/portraits/${gender === 'male' ? 'men' : 'women'}/${Math.floor(Math.random() * 100)}.jpg`
      };
    });

    // 根据搜索条件筛选
    const filteredUsers = mockUsers.filter(user => {
      let match = true;

      if (searchForm.userName) {
        if (!(user.userName.includes(searchForm.userName) ||
          user.id.includes(searchForm.userName) ||
          user.phone.includes(searchForm.userName))) {
          match = false;
        }
      }

      if (searchForm.status && user.status !== searchForm.status) {
        match = false;
      }

      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        const registerDate = new Date(user.registerTime);
        const startDate = new Date(searchForm.dateRange[0]);
        const endDate = new Date(searchForm.dateRange[1]);
        endDate.setHours(23, 59, 59, 999);

        if (registerDate < startDate || registerDate > endDate) {
          match = false;
        }
      }

      return match;
    });

    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    userList.value = filteredUsers.slice(start, end);
    pagination.total = filteredUsers.length;

    loading.value = false;
  }, 500);
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getUserList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.userName = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  pagination.currentPage = 1;
  getUserList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  getUserList();
};

// 页码变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  getUserList();
};

// 查看用户详情
const viewUserDetail = (row) => {
  currentUser.value = { ...row };
  detailDialogVisible.value = true;
};

// 编辑用户
const editUser = (row) => {
  editForm.id = row.id;
  editForm.userName = row.userName;
  editForm.phone = row.phone;
  editForm.email = row.email || '';
  editForm.gender = row.gender;
  editForm.age = row.age;
  editForm.status = row.status;
  editForm.address = row.address || '';
  editForm.remark = row.remark || '';

  editDialogVisible.value = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟保存操作
      const index = userList.value.findIndex(user => user.id === editForm.id);
      if (index !== -1) {
        userList.value[index] = {
          ...userList.value[index],
          userName: editForm.userName,
          phone: editForm.phone,
          email: editForm.email,
          gender: editForm.gender,
          age: editForm.age,
          status: editForm.status,
          address: editForm.address,
          remark: editForm.remark
        };

        ElMessage.success('更新成功');
        editDialogVisible.value = false;
      }
    }
  });
};

// 切换用户状态
const toggleUserStatus = (row) => {
  const statusText = row.status === 'disabled' ? '启用' : '禁用';

  ElMessageBox.confirm(
    `确定要${statusText}用户 "${row.userName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟状态切换
    const index = userList.value.findIndex(user => user.id === row.id);
    if (index !== -1) {
      userList.value[index].status = row.status === 'disabled' ? 'normal' : 'disabled';
      ElMessage.success(`${statusText}成功`);
    }
  }).catch(() => {
    // 取消操作
  });
};

// 导出用户列表
const exportUserList = () => {
  ElMessage.success('用户列表导出成功');
};

// 格式化状态
const formatStatus = (row) => {
  switch (row.status) {
    case 'normal':
      return '正常';
    case 'disabled':
      return '禁用';
    case 'unverified':
      return '未验证';
    default:
      return '未知状态';
  }
};

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'normal':
      return 'success';
    case 'disabled':
      return 'danger';
    case 'unverified':
      return 'info';
    default:
      return 'info';
  }
};
</script>

<style scoped>
.userlist-container {
  /* 根据规范，移除页面最外层元素的边距 */
}

.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
}

.search-card :deep(.el-form-item:last-child) {
  margin-left: auto;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  justify-content: center;
}

:deep(.el-table th.el-table__cell) {
  background-color: var(--el-table-header-bg-color);
  color: var(--el-text-color-primary);
  font-weight: 500;
}
</style>